#!/bin/bash
# -*- coding: utf-8 -*-
# 彩票爬虫启动脚本
# 可使用root用户运行
# 
# 功能：
# 1. 启动/停止/重启爬虫服务
# 2. 查看服务状态
# 3. 查看日志
# 4. 手动执行爬取任务
# 5. 系统健康检查
#
# 使用方法：
# chmod +x lottery_crawler_start.sh
# ./lottery_crawler_start.sh [start|stop|restart|status|logs|crawl|check|help]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 配置变量
PROJECT_DIR="/Users/ly/Desktop/lottery"
SCRIPTS_DIR="$PROJECT_DIR/scripts"
LOGS_DIR="$PROJECT_DIR/logs"
CONFIG_DIR="$PROJECT_DIR/config"
USER="lottery"

# 服务列表
SERVICES=(
    "lottery-current-crawler.timer"
    "mysqld"
    "redis"
)

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_debug() {
    echo -e "${PURPLE}[DEBUG]${NC} $1"
}

# 显示横幅
show_banner() {
    echo -e "${CYAN}"
    echo "========================================"
    echo "      彩票爬虫管理系统 v1.0"
    echo "========================================"
    echo -e "${NC}"
}

# 检查环境
check_environment() {
    # 检查项目目录
    if [[ ! -d "$PROJECT_DIR" ]]; then
        log_error "项目目录不存在: $PROJECT_DIR"
        log_error "请先运行安装脚本: centos8_install.sh"
        exit 1
    fi
    
    # 检查Python
    if ! command -v python3 &> /dev/null; then
        log_error "Python3 未安装"
        exit 1
    fi
    
    # 检查脚本文件
    local scripts=("lottery_history_crawler.py" "lottery_current_crawler.py")
    for script in "${scripts[@]}"; do
        if [[ ! -f "$SCRIPTS_DIR/$script" ]]; then
            log_warn "爬虫脚本不存在: $SCRIPTS_DIR/$script"
        fi
    done
}

# 启动服务
start_services() {
    log_step "启动彩票爬虫服务..."
    
    # 启动基础服务
    for service in "mysqld" "redis"; do
        if ! systemctl is-active --quiet $service; then
            log_info "启动 $service..."
            systemctl start $service
            sleep 2
        else
            log_info "$service 已运行"
        fi
    done
    
    # 启动爬虫定时器
    if ! systemctl is-active --quiet lottery-current-crawler.timer; then
        log_info "启动爬虫定时器..."
        systemctl start lottery-current-crawler.timer
    else
        log_info "爬虫定时器已运行"
    fi
    
    # 等待服务启动
    sleep 3
    
    # 检查服务状态
    local all_running=true
    for service in "${SERVICES[@]}"; do
        if systemctl is-active --quiet $service; then
            log_success "$service 运行正常"
        else
            log_error "$service 启动失败"
            all_running=false
        fi
    done
    
    if $all_running; then
        log_success "所有服务启动完成"
    else
        log_error "部分服务启动失败，请检查日志"
        exit 1
    fi
}

# 停止服务
stop_services() {
    log_step "停止彩票爬虫服务..."
    
    # 停止爬虫定时器
    if systemctl is-active --quiet lottery-current-crawler.timer; then
        log_info "停止爬虫定时器..."
        systemctl stop lottery-current-crawler.timer
    fi
    
    # 停止爬虫服务
    if systemctl is-active --quiet lottery-current-crawler.service; then
        log_info "停止当前期爬虫..."
        systemctl stop lottery-current-crawler.service
    fi
    
    if systemctl is-active --quiet lottery-history-crawler.service; then
        log_info "停止历史数据爬虫..."
        systemctl stop lottery-history-crawler.service
    fi
    
    log_success "爬虫服务已停止"
    
    # 询问是否停止基础服务
    read -p "是否停止MySQL和Redis服务？(y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        for service in "mysqld" "redis"; do
            if systemctl is-active --quiet $service; then
                log_info "停止 $service..."
                systemctl stop $service
            fi
        done
        log_success "所有服务已停止"
    fi
}

# 重启服务
restart_services() {
    log_step "重启彩票爬虫服务..."
    stop_services
    sleep 3
    start_services
}

# 查看服务状态
show_status() {
    log_step "查看服务状态..."
    echo
    
    printf "%-35s %-10s %-15s\n" "服务名称" "状态" "自启动"
    echo "--------------------------------------------------------"
    
    for service in "${SERVICES[@]}"; do
        if systemctl is-active --quiet $service; then
            status="${GREEN}运行中${NC}"
        else
            status="${RED}已停止${NC}"
        fi
        
        if systemctl is-enabled --quiet $service 2>/dev/null; then
            enabled="${GREEN}已启用${NC}"
        else
            enabled="${RED}已禁用${NC}"
        fi
        
        printf "%-35s %-20s %-25s\n" "$service" "$status" "$enabled"
    done
    
    echo
    
    # 显示定时器状态
    log_info "定时器状态:"
    systemctl list-timers lottery-* --no-pager
    
    echo
    
    # 显示最近的爬虫执行记录
    log_info "最近的爬虫执行记录:"
    journalctl -u lottery-current-crawler.service --no-pager -n 5
}

# 查看日志
show_logs() {
    log_step "查看系统日志..."
    
    echo "选择要查看的日志:"
    echo "1) 当前期爬虫日志"
    echo "2) 历史数据爬虫日志"
    echo "3) 系统服务日志"
    echo "4) 应用日志文件"
    echo "5) 实时日志"
    
    read -p "请选择 (1-5): " -n 1 -r
    echo
    
    case $REPLY in
        1)
            journalctl -u lottery-current-crawler.service -f
            ;;
        2)
            journalctl -u lottery-history-crawler.service -f
            ;;
        3)
            journalctl -u lottery-current-crawler.timer -f
            ;;
        4)
            if [[ -d "$LOGS_DIR" ]]; then
                echo "可用的日志文件:"
                ls -la "$LOGS_DIR"/*.log 2>/dev/null || echo "没有找到日志文件"
                echo
                read -p "请输入日志文件名 (或按Enter查看最新的): " log_file
                if [[ -z "$log_file" ]]; then
                    tail -f "$LOGS_DIR"/*.log 2>/dev/null || echo "没有找到日志文件"
                else
                    tail -f "$LOGS_DIR/$log_file"
                fi
            else
                log_error "日志目录不存在: $LOGS_DIR"
            fi
            ;;
        5)
            tail -f /var/log/messages | grep lottery
            ;;
        *)
            log_error "无效选择"
            ;;
    esac
}

# 手动执行爬取任务
manual_crawl() {
    log_step "手动执行爬取任务..."
    
    echo "选择要执行的任务:"
    echo "1) 抓取所有彩种当前期数据"
    echo "2) 抓取单个彩种当前期数据"
    echo "3) 抓取所有彩种历史数据"
    echo "4) 抓取单个彩种历史数据"
    echo "5) 测试数据库连接"
    
    read -p "请选择 (1-5): " -n 1 -r
    echo
    
    cd "$SCRIPTS_DIR" || exit 1
    
    case $REPLY in
        1)
            log_info "开始抓取所有彩种当前期数据..."
            sudo -u $USER python3 run_crawler.py --mode latest
            ;;
        2)
            echo "支持的彩种: ssq, dlt, fc3d, qlc, pl3, pl5, qxc, kl8"
            read -p "请输入彩种代码: " lottery_type
            log_info "开始抓取 $lottery_type 当前期数据..."
            sudo -u $USER python3 run_crawler.py --mode latest --lottery "$lottery_type"
            ;;
        3)
            read -p "请输入要抓取的期数 (默认50): " count
            count=${count:-50}
            log_info "开始抓取所有彩种历史${count}期数据..."
            sudo -u $USER python3 run_crawler.py --mode history-smart --count "$count"
            ;;
        4)
            echo "支持的彩种: ssq, dlt, fc3d, qlc, pl3, pl5, qxc, kl8"
            read -p "请输入彩种代码: " lottery_type
            read -p "请输入要抓取的期数 (默认50): " count
            count=${count:-50}
            log_info "开始抓取 $lottery_type 历史${count}期数据..."
            sudo -u $USER python3 run_crawler.py --mode history-smart --lottery "$lottery_type" --count "$count"
            ;;
        5)
            log_info "测试数据库连接..."
            mysql -u lottery -ppassword123 -e "USE lottery_api; SELECT COUNT(*) as total_records FROM lottery_results; SHOW TABLE STATUS;"
            ;;
        *)
            log_error "无效选择"
            ;;
    esac
}

# 系统健康检查
health_check() {
    log_step "系统健康检查..."
    
    local issues=0
    
    # 检查服务状态
    echo "1. 服务状态检查:"
    for service in "${SERVICES[@]}"; do
        if systemctl is-active --quiet $service; then
            log_success "$service 运行正常"
        else
            log_error "$service 未运行"
            ((issues++))
        fi
    done
    
    echo
    
    # 检查磁盘空间
    echo "2. 磁盘空间检查:"
    local disk_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    if [[ $disk_usage -gt 80 ]]; then
        log_warn "磁盘空间不足: ${disk_usage}%"
        ((issues++))
    else
        log_success "磁盘空间正常: ${disk_usage}%"
    fi
    
    echo
    
    # 检查内存使用
    echo "3. 内存使用检查:"
    local mem_usage=$(free | awk 'NR==2{printf "%.2f", $3*100/$2 }')
    if (( $(echo "$mem_usage > 80" | bc -l) )); then
        log_warn "内存使用过高: ${mem_usage}%"
        ((issues++))
    else
        log_success "内存使用正常: ${mem_usage}%"
    fi
    
    echo
    
    # 检查数据库连接
    echo "4. 数据库连接检查:"
    if mysql -u lottery -ppassword123 -e "SELECT 1" >/dev/null 2>&1; then
        log_success "数据库连接正常"
        
        # 检查数据表
        local table_count=$(mysql -u lottery -ppassword123 -e "USE lottery_api; SHOW TABLES;" 2>/dev/null | wc -l)
        if [[ $table_count -gt 1 ]]; then
            log_success "数据表正常 ($((table_count-1)) 个表)"
        else
            log_warn "数据表可能缺失"
            ((issues++))
        fi
    else
        log_error "数据库连接失败"
        ((issues++))
    fi
    
    echo
    
    # 检查Redis连接
    echo "5. Redis连接检查:"
    if redis-cli ping >/dev/null 2>&1; then
        log_success "Redis连接正常"
    else
        log_error "Redis连接失败"
        ((issues++))
    fi
    
    echo
    
    # 检查Python依赖
    echo "6. Python依赖检查:"
    if python3 -c "import requests, pymysql, redis, loguru" 2>/dev/null; then
        log_success "Python依赖正常"
    else
        log_error "Python依赖缺失"
        ((issues++))
    fi
    
    echo
    
    # 检查日志文件
    echo "7. 日志文件检查:"
    if [[ -d "$LOGS_DIR" ]]; then
        local log_count=$(find "$LOGS_DIR" -name "*.log" | wc -l)
        if [[ $log_count -gt 0 ]]; then
            log_success "日志文件正常 ($log_count 个文件)"
        else
            log_warn "没有找到日志文件"
        fi
    else
        log_warn "日志目录不存在"
        ((issues++))
    fi
    
    echo
    
    # 总结
    if [[ $issues -eq 0 ]]; then
        log_success "系统健康状态良好，没有发现问题"
    else
        log_warn "发现 $issues 个问题，建议检查和修复"
    fi
    
    # 显示系统信息
    echo
    echo "系统信息:"
    echo "  操作系统: $(cat /etc/centos-release 2>/dev/null || echo '未知')"
    echo "  Python版本: $(python3 --version 2>/dev/null || echo '未安装')"
    echo "  MySQL版本: $(mysql --version 2>/dev/null | awk '{print $3}' || echo '未安装')"
    echo "  Redis版本: $(redis-server --version 2>/dev/null | awk '{print $3}' || echo '未安装')"
    echo "  系统负载: $(uptime | awk -F'load average:' '{print $2}')"
    echo "  运行时间: $(uptime -p)"
}

# 显示帮助信息
show_help() {
    show_banner
    echo "彩票爬虫管理脚本"
    echo
    echo "使用方法:"
    echo "  $0 [命令]"
    echo
    echo "可用命令:"
    echo "  start     - 启动爬虫服务"
    echo "  stop      - 停止爬虫服务"
    echo "  restart   - 重启爬虫服务"
    echo "  status    - 查看服务状态"
    echo "  logs      - 查看日志"
    echo "  crawl     - 手动执行爬取任务"
    echo "  check     - 系统健康检查"
    echo "  help      - 显示帮助信息"
    echo
    echo "示例:"
    echo "  $0 start          # 启动所有服务"
    echo "  $0 status         # 查看服务状态"
    echo "  $0 crawl          # 手动执行爬取任务"
    echo "  $0 check          # 系统健康检查"
    echo
    echo "配置文件: $CONFIG_DIR/.env"
    echo "日志目录: $LOGS_DIR"
    echo "脚本目录: $SCRIPTS_DIR"
    echo
}

# 主函数
main() {
    # 检查环境
    check_environment
    
    # 处理命令行参数
    case "${1:-help}" in
        start)
            show_banner
            start_services
            ;;
        stop)
            show_banner
            stop_services
            ;;
        restart)
            show_banner
            restart_services
            ;;
        status)
            show_banner
            show_status
            ;;
        logs)
            show_banner
            show_logs
            ;;
        crawl)
            show_banner
            manual_crawl
            ;;
        check)
            show_banner
            health_check
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            echo
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
